package qc.module.cms.mapper;

import org.apache.commons.lang3.StringUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
import qc.common.core.enums.ResourceStatusFlagEnum;
import qc.module.cms.dto.link.LinkDto;
import qc.module.cms.entity.Link;

import java.util.List;

/**
 * LinkMapper
 *
 * @author QuCheng Tech
 * @create 2023/5/25
 */
@Mapper
public interface LinkMapper {
    LinkMapper MAPPER = Mappers.getMapper(LinkMapper.class);

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "odr", ignore = true)
    @Mapping(target = "flag", ignore = true)
    Link toEntity(LinkDto dto);

    @Mapping(target = "flag", source = "flag.index")
    LinkDto toDto(Link en);

    List<LinkDto> toDtoList(List<Link> list);

    default Link LinkDtoToEntity(LinkDto dto) {
        //DTO转换为Entity
        Link en = LinkMapper.MAPPER.toEntity(dto);
        //ID转换，用于修改时赋值，新增时在写入数据库前再生成新ID
        //if (!StringUtils.isBlank(dto.getId())) {
        //    try {
        //        int id = Integer.parseInt(dto.getId());
        //        en.setId(id);
        //    } catch (NumberFormatException exception) {
        //    }
        //}
        if (dto.getId() > 0x0)
            en.setId(dto.getId());
        //排序号需进行判空，非空时进行转换
        if (!StringUtils.isBlank(dto.getOdr())) {
            try {
                int order = Integer.parseInt(dto.getOdr());
                en.setOdr(order);
            } catch (NumberFormatException exception) {
            }
        }
        //处理标记，非空时进行转换，空值时使用默认
        Integer flag = null;
        if (!StringUtils.isBlank(dto.getFlag())) {
            try {
                flag = Integer.parseInt(dto.getFlag());
            } catch (NumberFormatException exception) {
                //转换错误不处理，使用默认状态
            }
        }
        en.setFlag(getResourceStatusFlagEnum(flag));

        return en;
    }

    static ResourceStatusFlagEnum getResourceStatusFlagEnum(Integer index) {
        if (index != null && index > 0x0) {
            for (ResourceStatusFlagEnum item : ResourceStatusFlagEnum.values()) {
                if (item.getIndex() == index) {//判断序号使用getIndex，判断内容使用getName
                    return item;
                }
            }
        }
        return ResourceStatusFlagEnum.NORMAL;
    }
}
